<?php

namespace App\Repositories;

use App\Models\Template;
use App\Models\TemplateMapping;

class TemplateRepository
{

    public function getList(int $uid): array
    {
        $res = Template::query()
            ->where("status", 1)
            ->get(['id', 'title', 'summary','tip'])
            ->toArray();

        foreach ($res as $k => &$v) {
            $count = TemplateMapping::query()->where(['template_id' => $v['id'], 'uid' => $uid])->count("id"); //取消模板
            $v['status'] = $count > 0 ? 0 : 1;
        }

        return $res;
    }

    /**
     * 关闭模板增加记录
     */
    public function updateMapping(int $id, int $uid)
    {
        if (!$id || !$uid)
            return retFail("参数错误");

        $res = TemplateMapping::query()->where("id", $id)->first();
        if (empty($res)) {
            TemplateMapping::query()->create([
                "template_id" => $id,
                "uid" => $uid
            ]);
            return retSuc([], "已关闭");
        }

        TemplateMapping::query()->where("id", $id)->delete();
        return retSuc([], "已开启");
    }

}